package com.jili.aspect;

import com.jili.annotion.UserLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * ClassName: UserLogAspect
 * Package com.jili.aspect
 * Description:
 *
 * @Author: 廖继礼
 * @Create: 2025/3/9
 * @Version: v1.0
 */
@Aspect
@Component
@Slf4j
public class UserLogAspect {

    @Pointcut("@annotation(com.jili.annotion.UserLog) && execution(public * *(..))")
    public void pointCut() {

    }

    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();
        log.info("args is {}", args);

        // 获取注解
        UserLog userLogAnnotation = method.getAnnotation(UserLog.class);
        if (userLogAnnotation != null && args != null && args.length > 0) {
            // 使用PropertyUtils.getProperty 获取userId
            Object userId = PropertyUtils.getProperty(args[0], userLogAnnotation.userId());
            Object orderId = PropertyUtils.getProperty(args[1], userLogAnnotation.orderId());
            log.info("userId is {}", userId);
            log.info("orderId is {}", orderId);
        }
        try {
            return joinPoint.proceed();
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }


}
